package com.yao.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yao.aspect.LogAspect;
import com.yao.domain.Ebook;
import com.yao.domain.EbookExample;
import com.yao.mapper.EbookMapper;
import com.yao.req.EbookQueryReq;
import com.yao.req.EbookReq;
import com.yao.req.EbookSaveReq;
import com.yao.resp.EbookQueryResp;
import com.yao.resp.EbookResp;
import com.yao.resp.PageResp;
import com.yao.util.CopyUtil;
import com.yao.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author : hzyao
 * @date : 17:39 2021/7/27
 */
@Service
public class EbookService {

    private final static Logger LOG = LoggerFactory.getLogger(LogAspect.class);

    @Resource
    private EbookMapper ebookMapper;
    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req) {

        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if(!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }
        if(!ObjectUtils.isEmpty(req.getCategory2Id())) {
            criteria.andCategory2IdEqualTo( req.getCategory2Id() );
        }
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);
        PageInfo<Ebook> pageInfo = new PageInfo();
        LOG.info("总行数:{}",pageInfo.getTotal());
        LOG.info("总页数:{}",pageInfo.getPages());
//        List<EbookResp> respList = new ArrayList<>();
//        for (Ebook ebook : ebookList) {
//            EbookResp ebookResp = new EbookResp();
//            BeanUtils.copyProperties(ebook,ebookResp);
//            respList.add(ebookResp);
//
//        }
        List<EbookQueryResp> respList = CopyUtil.copyList(ebookList, EbookQueryResp.class);
        PageResp<EbookQueryResp> ebookPageResp = new PageResp<>();
        ebookPageResp.setTotal(pageInfo.getTotal());
        ebookPageResp.setList(respList);
        return  ebookPageResp;
    }


    public void save(EbookSaveReq req){
        Ebook ebook = CopyUtil.copy(req,Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())){
            //雪花算法
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        }else{
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }
    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }

}
